package com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study4.controller;

import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class TianXingApiHttpURLConnectionController {
    /**
     * 使用  HttpURLConnection get和post请求第三方api
     *
     * @return
     */
    @GetMapping("/test")
    public Object test1(@RequestParam Map<String, String> map) throws Exception {
        String requestData = "";
        //拼装url
        //URLEncoder.encode对汉字进行编码，服务器进行解码设置，解决中文乱码
        String key = map.get("key");
        String type = map.get("type");
        String city = map.get("city");
        String pathUrl = "https://apis.tianapi.com/tianqi/index";
        String lastUrl = pathUrl + "?key=" + URLEncoder.encode(key, "utf-8") + "&city=" + city + "&type=" + type;
        URL url = new URL(lastUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();//开发访问此连接
        // 设置请求头
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // 设置访问时长和相应时长
        urlConn.setConnectTimeout(5000); // 设置连接时间为5秒
        urlConn.setReadTimeout(5000);  // 设置读取时间为5秒
        int code = urlConn.getResponseCode();  // 获取响应码
        if (code == 200) {  // 响应成功，获得相应数据
            InputStream is = urlConn.getInputStream();  // 得到数据流  输入流
            byte[] buffer = new byte[1024];
            int length = 0;
            StringBuilder data = new StringBuilder();
            while ((length = is.read(buffer)) != -1) {
                String str = new String(buffer, 0, length);
                data.append(str);
            }
            System.out.println(data.toString());
            requestData = data.toString();
            is.close();
        }
        return requestData;
    }
    // post方式
    @PostMapping("/test1")
    public Object test2(@RequestBody Map<String, String> map) throws Exception {

//        String tianapi_data = "";
//        try {
//            URL url = new URL("https://apis.tianapi.com/tianqi/index");
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            conn.setRequestMethod("POST");
//            conn.setConnectTimeout(5000);
//            conn.setReadTimeout(5000);
//            conn.setDoOutput(true);
//            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//            OutputStream outputStream = conn.getOutputStream();
//            String key = map.get("key");
//            String city = map.get("city");
//            String content = "key="+key+"&city="+URLEncoder.encode(city, "utf-8")+"&type=1";
//            outputStream.write(content.getBytes());
//            outputStream.flush();
//            outputStream.close();
//            InputStream inputStream = conn.getInputStream();
//            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
//            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//            StringBuilder tianapi = new StringBuilder();
//            String temp = null;
//            while (null != (temp = bufferedReader.readLine())) {
//                tianapi.append(temp);
//            }
//            tianapi_data = tianapi.toString();
//            inputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println(tianapi_data);
//    }

        String requestData = "";
        String pathUrl = "https://apis.tianapi.com/tianqi/index";
        URL url = new URL(pathUrl);
        //拼装url
        //URLEncoder.encode对汉字进行编码，服务器进行解码设置，解决中文乱码
        String key = map.get("key");
        String type = map.get("type");
        String city = map.get("city");
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();//开发访问此连接
        // 设置请求方式
        urlConn.setRequestMethod("POST");
        // 设置是否向远程服务写入数据
        urlConn.setDoOutput(true);
        // 设置是否从远程服务读取数据
        urlConn.setDoInput(true);
        // 设置是否使用缓存，post请求不能使用缓存
        urlConn.setUseCaches(false);
        // 设置连接主机服务器超时时间
        urlConn.setConnectTimeout(50000);
        // 设置读取主机服务器返回数据超时时间
        urlConn.setReadTimeout(50000);
        // 设置请求头，接受数据的格式
        urlConn.setRequestProperty("Accept","application/json");
        urlConn.setRequestProperty("Connection","keep-alive");
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // 连接
        urlConn.connect();
        //获取响应
        OutputStream outputStream = urlConn.getOutputStream();
        //post参数
        String content = "key="+key+"&type="+type+"&city="+URLEncoder.encode(city, "utf-8");
        outputStream.write(content.getBytes());//上传参数
        outputStream.flush();
        outputStream.close();
        int code = urlConn.getResponseCode();
        if(code == 200) {//相应成功，获得相应的数据
            InputStream is = urlConn.getInputStream();//得到数据流（输入流）
            StringBuffer str = new StringBuffer();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            try{
                String line = "";
                while((line = br.readLine()) != null) {
                    str.append(line);
                }
                System.out.println(str.toString());
                requestData = str.toString();
            } finally {
                br.close();
                is.close();
            }
        }
        return requestData;
    }
}
